var Base64 = (function() {
	var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
	function utf8Encode(string) {
		string = string.replace(/\r\n/g, "\n");
		var utftext = "";
		for (var n = 0; n < string.length; n++) {
			var c = string.charCodeAt(n);
			if (c < 128) {
				utftext += String.fromCharCode(c);
			} else if ((c > 127) && (c < 2048)) {
				utftext += String.fromCharCode((c >> 6) | 192);
				utftext += String.fromCharCode((c & 63) | 128);
			} else {
				utftext += String.fromCharCode((c >> 12) | 224);
				utftext += String.fromCharCode(((c >> 6) & 63) | 128);
				utftext += String.fromCharCode((c & 63) | 128);
			}
		}
		return utftext;
	}
	return {
		encode : function(input) {
			var output = "";
			var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
			var i = 0;
			input = utf8Encode(input);
			while (i < input.length) {
				chr1 = input.charCodeAt(i++);
				chr2 = input.charCodeAt(i++);
				chr3 = input.charCodeAt(i++);
				enc1 = chr1 >> 2;
				enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
				enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
				enc4 = chr3 & 63;
				if (isNaN(chr2)) {
					enc3 = enc4 = 64;
				} else if (isNaN(chr3)) {
					enc4 = 64;
				}
				output = output + keyStr.charAt(enc1) + keyStr.charAt(enc2)
						+ keyStr.charAt(enc3) + keyStr.charAt(enc4);
			}
			return output;
		}
	};
})();

Ext.override(Ext.grid.GridPanel, {
	
	outExcelXml:function(includeHidden,title){
		var data=this.getExcelXml(includeHidden,title);
		if(!data)
		return;
		
//		if ((!Ext.isIE7) && (!Ext.isIE6))
//						document.location = 'data:application/vnd.ms-excel;base64,'
//								+ Base64.encode(data);
//					else {
						if (!Ext.fly('frmDummy')) {
//							var  frame = document.createElement('iframe');
//							frame.id='frmDummyExceldatas';
//							frame.name='frmDummyExceldatas';
//							frame.className= 'x-hidden';
//                            frame.src=Ext.SSL_SECURE_URL;
//							document.body.appendChild(frame);
							
							var frm = document.createElement('form');
							frm.id = 'frmDummy';
							frm.name = 'frmDummy';
							frm.action = 'js/public/excel.jsp';
							frm.method='POST';
							frm.encoding = 'multipart/form-data';
							frm.enctype = 'multipart/form-data';
							frm.target = 'frmDummyExceldatas';              
							frm.className = 'x-hidden';
							var inp = document.createElement('input');
							inp.type = "hidden";
							inp.value = data;
							inp.id = "exceldatas";
							inp.name = "exceldatas"
							frm.appendChild(inp);
							document.body.appendChild(frm);
						    frm.submit();
						    inp.value = '';	
						}else{
						var inp =document.getElementById("exceldatas");
						inp.value=data;
						var frmDummy =document.getElementById("frmDummy");
						frmDummy.submit();
						inp.value = '';
						}
						
//						var formboj=Ext.Ajax.request({
//							url : '/ifmis/fasp/excel.jsp',
//							method : 'POST',
//							form : Ext.fly('frmDummy'),
//							isUpload : true,
//							success:function(){
//							},
//							id:'exceldatasifrom'
//								// params: { data: data }
//						});
							
					//}
	
	
	},
	
	getExcelXml : function(includeHidden,title) {
			if(this.store.data.items<=0){
			Ext.Msg.alert("不存在数据","在数据列表中未有可导出的数据.");	
			return null;
			}
		var worksheet = this.createWorksheet(includeHidden,title);
		var totalWidth = this.getColumnModel().getTotalWidth(includeHidden);
		return '<xml version="1.0" encoding="UTF-8">'
				+ '<ss:Workbook xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:o="urn:schemas-microsoft-com:office:office">'
				+ '<o:DocumentProperties><o:Title>'
				+ (title?title:this.title)
				+ '</o:Title></o:DocumentProperties>'
				+ '<ss:ExcelWorkbook>'
				+ '<ss:WindowHeight>'
				+ worksheet.height
				+ '</ss:WindowHeight>'
				+ '<ss:WindowWidth>'
				+ worksheet.width
				+ '</ss:WindowWidth>'
				+ '<ss:ProtectStructure>False</ss:ProtectStructure>'
				+ '<ss:ProtectWindows>False</ss:ProtectWindows>'
				+ '</ss:ExcelWorkbook>'
				+ '<ss:Styles>'
				+ '<ss:Style ss:ID="Default">'
				+ '<ss:Alignment ss:Vertical="Top" ss:WrapText="1" />'
				+ '<ss:Font ss:FontName="arial" ss:Size="10" />'
				+ '<ss:Interior ss:Pattern="Solid"  />'
				+ '<ss:NumberFormat />'
				+ '<ss:Protection />'
				+ '</ss:Style>'
				+ '<ss:Style ss:ID="title">'
				+ '<ss:Borders />'
				+ '<ss:Font />'
				+ '<ss:Alignment ss:WrapText="1" ss:Vertical="Center" ss:Horizontal="Center" />'
				+ '<ss:NumberFormat ss:Format="@" />' + '</ss:Style>'
				+ '<ss:Style ss:ID="headercell">'
				+ '<ss:Borders>'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Top" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Bottom" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Left" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Right" />'
				+ '</ss:Borders>'
				+ '<ss:Font ss:Bold="1" ss:Size="10" />'
				+ '<ss:Alignment ss:WrapText="1" ss:Horizontal="Center" />'
				+ '<ss:Interior ss:Pattern="Solid"  />'
				+ '</ss:Style>' + '<ss:Style ss:ID="even">'
				+ '<ss:Interior ss:Pattern="Solid"  />'
				+ '<ss:Borders>'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Top" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Bottom" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Left" />'
				+ '<ss:Border  ss:Weight="1" ss:LineStyle="Continuous" ss:Position="Right" />'
				+ '</ss:Borders>'
				+ '</ss:Style>'
				+ '<ss:Style ss:Parent="even" ss:ID="evendate">'
				+ '<ss:NumberFormat ss:Format="yyyy-mm-dd" />' + '</ss:Style>'
				+ '<ss:Style ss:Parent="even" ss:ID="evenint">'
				+ '<ss:NumberFormat ss:Format="0" />' + '</ss:Style>'
				+ '<ss:Style ss:Parent="even" ss:ID="evenfloat">'
				+ '<ss:NumberFormat ss:Format="0.000" />' + '</ss:Style>'
				+ '</ss:Styles>' + worksheet.xml + '</ss:Workbook>';
	},

	
	
	headerGroups:function(colsHeader){
				var strbuf=[];

		for(var i=0;i<colsHeader.length;i++){
		 strbuf.push('<ss:Row ss:AutoFitHeight="0"  ss:Height="22">');
		    for(var j=0;j<colsHeader[i].length;j++){
		    	 strbuf.push('  <ss:Cell ss:MergeAcross="');strbuf.push(colsHeader[i][j].colspan-1);strbuf.push('"  ss:StyleID="headercell">');
		         strbuf.push('<ss:Data ss:Type="String">');strbuf.push(colsHeader[i][j].header);strbuf.push('</ss:Data>	<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>');

		    } 
		 strbuf.push('</ss:Row>');
		}
		return strbuf.join("");
	},
	
	
	createWorksheet : function(includeHidden,title) {
		// Calculate cell data types and extra class names which affect
		// formatting
		var cellType = [];
		var cellTypeClass = [];
		var cm = this.getColumnModel();
		var totalWidthInPixels = 0;
		var colXml = '';
		var headerXml = '';
		var visibleColumnCountReduction = 0;
		var dataIndex=[];
	
		for (var i = 0; i < cm.getColumnCount(); i++) {
			if (includeHidden || !cm.isHidden(i)) {
				var w = cm.getColumnWidth(i)
				totalWidthInPixels += w;
									var  columnHeader_xml=cm.getColumnHeader(i);

				if (columnHeader_xml === "") {
					cellType.push("None");
					cellTypeClass.push("");
					++visibleColumnCountReduction;
				} else {
					colXml += '<ss:Column ss:AutoFitWidth="1" ss:Width="' + w
							+ '" />';
					headerXml += '<ss:Cell ss:StyleID="headercell">'
							+ '<ss:Data ss:Type="String">'
							+(columnHeader_xml?columnHeader_xml:" ")
							+ '</ss:Data>'
							+ '<ss:NamedCell ss:Name="Print_Titles" /></ss:Cell>';
					var fld = this.store.recordType.prototype.fields.get(cm
							.getDataIndex(i));
							
				   if(fld){
				   
					switch (fld.type) {
						case "int" :
							cellType.push("Number");
							cellTypeClass.push("int");
							break;
						case "float" :
							cellType.push("Number");
							cellTypeClass.push("float");
							break;
						case "BigDecimal" :
							cellType.push("Number");
							cellTypeClass.push("");
							break;
						case "number" :
							cellType.push("Number");
							cellTypeClass.push("");
							break;
						case "float" :
							cellType.push("Number");
							cellTypeClass.push("float");
							break;
						case "bool" :
						case "boolean" :
							cellType.push("String");
							cellTypeClass.push("");
							break;
						case "date" :
							cellType.push("DateTime");
							cellTypeClass.push("date");
							break;
						default :
							cellType.push("String");
							cellTypeClass.push("");
							break;
					}
				}else{
							cellType.push("String");
							cellTypeClass.push("");
				
				}
				
				}
				
			}
			dataIndex.push(cm.getDataIndex(i));
		}
		var visibleColumnCount = cellType.length - visibleColumnCountReduction;

		var result = {
			height : 9000,
			width : Math.floor(totalWidthInPixels * 30) + 50
		};

		// Generate worksheet header details.
	  
		//var pand=this.getSelectionModel().width?true:false;
		var array=this.getSelectionModel().getSelections();
		
				var it=array.length>0?array:this.store.data.items; 
				var l = it.length;
			var  headerGroupsStr="";
			var groupsColumnCount=0;
					if(cm.rows){
					groupsColumnCount=cm.rows.length;
				    headerGroupsStr=this.headerGroups(cm.rows);
					}
		var t =['<ss:Worksheet ss:Name="'
				+ (title?title:this.title)
				+ '">'
				+ '<ss:Names>'
				+ '<ss:NamedRange ss:Name="Print_Titles" ss:RefersTo="=\''
				+ (title?title:this.title)
				+ '\'!R1:R2" />'
				+ '</ss:Names>'
				+ '<ss:Table x:FullRows="1" x:FullColumns="1"'
				+ ' ss:ExpandedColumnCount="'
				+ visibleColumnCount
				+ '" ss:ExpandedRowCount="'
				+ (l+ 2+groupsColumnCount)
				+ '">'
				+ colXml
				+ '<ss:Row ss:Height="38">'
				+ '<ss:Cell ss:StyleID="title" ss:MergeAcross="'
				+ (visibleColumnCount - 1)
				+ '">'
				+ '<ss:Data xmlns:html="http://www.w3.org/TR/REC-html40" ss:Type="String">'
				+ '<html:B> '+(title?title:this.title)+'</html:B></ss:Data><ss:NamedCell ss:Name="Print_Titles" />'
				+ '</ss:Cell>' + '</ss:Row>'+headerGroupsStr + '<ss:Row ss:AutoFitHeight="1" ss:Height="25.5">'
				+ headerXml + '</ss:Row>'];
				
			
			
				var colcount=cm.getColumnCount();
				
		for (var i = 0 ; i < l; i++) {
			t.push('<ss:Row ss:Height="18">');
			var cellClass =  'even';
			r = it[i].data;
			var k = 0;
           
			for (var j = 0; j < colcount; j++) {
				if (includeHidden || !cm.isHidden(j)) {
					
					var v = r[dataIndex[j]];
					if (cellType[k] !== "None") {
						t.push( '<ss:Cell ss:StyleID="');
						t.push( cellClass);
						t.push( cellTypeClass[k]);
						t.push('"><ss:Data ss:Type="');
						t.push(cellType[k] );
						t.push( '">');
//						if(cm.config[j].renderer){
//						    t.append(cm.config[j].renderer(v));
//						}else
						
						t.push(v?v:'');
//						if (cellType[k] == 'DateTime') {
//							t += v.format('Y-m-d');
//						} else {
							
						//}
						t.push('</ss:Data></ss:Cell>');
					}
					k++;
				}
			}
			t.push( '</ss:Row>');
		}

		result.xml = t.join("")
				+ '</ss:Table>'
				+ '<x:WorksheetOptions>'
				+ '<x:PageSetup>'
				+ '<x:Layout x:CenterHorizontal="1" x:Orientation="Landscape" />'
				+ '<x:Footer x:Data="Page &amp;P of &amp;N" x:Margin="0.5" />'
				+ '<x:PageMargins x:Top="0.5" x:Right="0.5" x:Left="0.5" x:Bottom="0.8" />'
				+ '</x:PageSetup> <x:FitToPage /> <x:Print>'
				+ '<x:PrintErrors>Blank</x:PrintErrors>'
				+ '<x:FitWidth>1</x:FitWidth>'
				+ '<x:FitHeight>32767</x:FitHeight> <x:ValidPrinterInfo />'
				+ '<x:VerticalResolution>600</x:VerticalResolution>'
				+ '</x:Print> <x:Selected />'
				+ '<x:DoNotDisplayGridlines />'
				+ '<x:ProtectObjects>False</x:ProtectObjects>'
				+ '<x:ProtectScenarios>False</x:ProtectScenarios>'
				+ '</x:WorksheetOptions> </ss:Worksheet>';
		return result;
	}
});
